import React, {useState, useEffect, useRef, useImperativeHandle} from 'react'
import {Button, Modal, Form, Select, Row, Col, Collapse, Popconfirm} from 'antd'

import moment from 'moment'
import ActivityCashback from './ActivityCashback'
import MaterialObject from './MaterialObject'
import RentFree from './RentFree'
import DeferredRent from './DeferredRent'
import styles from './index.less'
import 'moment/locale/zh-cn'
// import {selectType} from '../constant'
const {Panel} = Collapse
const activeTypeList: any = [
	{
		label: '返现',
		value: 1,
	},
	{
		label: '实物',
		value: 2,
	},
	{
		label: '免租',
		value: 3,
	},
	{
		label: '延租',
		value: 4,
	},
]
const customizeHeader = (value: string) => (
	<div>
		<div className={styles.tip} />
		{value}
	</div>
)
const rewardInfo = (props: {
	routerQuery: any
	driverRewardRules: any
	cRef: any
}) => {
	const {routerQuery, driverRewardRules, cRef} = props
	const {detailRecord} = driverRewardRules
	const [visible, setVisible] = useState(false)
	const [activeList, setActiveList] = useState<any>([])
	const [noActiveList, setNoActiveList] = useState<any>([])

	const [rewardInfoFrom] = Form.useForm()

	const childActivityCashback = useRef<any>(null)
	const childMaterialObject = useRef<any>(null)
	const childRentFree = useRef<any>(null)
	const childDeferredRent = useRef<any>(null)
	const onActiveTypeChange = () => {
		const formData = rewardInfoFrom.getFieldsValue()
		const l = activeList.filter(
			(item: any) => item.value !== formData.activeType,
		)
		setActiveList(() => l)
		const ids = l.map((item: any) => item.value)
		const n = activeTypeList
			?.filter((item: any) => !ids.includes(item.value))
			.map((item: any) => item.value)
		setNoActiveList(n)
		setVisible(false)
		rewardInfoFrom.resetFields()
	}
	// 新增初始化
	useEffect(() => {
		if (routerQuery.pageType === 'add') {
			setActiveList(activeTypeList)
			setNoActiveList([])
		}
	}, [routerQuery])

	// 初始化详情数据
	useEffect(() => {
		if (
			routerQuery.pageType === 'edit' ||
			routerQuery.pageType === 'detail' ||
			routerQuery.pageType === 'process'
		) {
			const ids = detailRecord?.map((item: any) => item?.activitiesType)
			const l = activeTypeList?.filter(
				(item: any) => !ids?.includes(item.value),
			)
			const n = activeTypeList
				?.filter((item: any) => ids?.includes(item.value))
				.map((item: any) => item.value)
			setActiveList(l)
			setNoActiveList(n)
		}
	}, [detailRecord])

	useImperativeHandle(cRef, () => ({
		clearCostitemList: () => {
			childActivityCashback?.current?.clearCostitemList()
			childRentFree?.current?.clearCostitemList()
			childMaterialObject?.current?.clearCostitemList()
		},
		// changeVal 就是暴露给父组件的方法
		allFormData: async (callBack: any) => {
			const result = []
			const childActivityBise =
				await childActivityCashback?.current?.getFormData()
			const childActivityOther =
				await childActivityCashback?.current?.getConditions()

			const materialObjectBise =
				await childMaterialObject?.current?.getFormData()
			const materialObjectOther =
				await childMaterialObject?.current?.getConditions()
			const rentFreeBise = await childRentFree?.current?.getFormData()
			const deferredRentBise =
				await childDeferredRent?.current?.getFormData()
			if (childActivityCashback?.current) {
				let rewardDetailsList: any
				if (childActivityBise.releaseTime !== 3) {
					rewardDetailsList = [
						{
							leaseTerm: null,
							examinationInterval:
								childActivityBise?.examinationInterval,
							entityType: null,
							issueKind: null,
							extendedRentalDays: null,
							amount: childActivityBise?.amount,
						},
					]
				} else {
					rewardDetailsList = childActivityCashback?.current
						?.getList()
						?.map((item: any) => {
							const newItem = item
							if (newItem?.id?.toString().includes('ID')) {
								delete newItem.id
							}
							newItem.examinationInterval =
								childActivityBise?.examinationInterval
							return newItem
						})
				}
				result.push({
					activitiesType: 1,
					...childActivityBise,
					rewardDetailsList,
					...childActivityOther,
					completionTime: childActivityOther?.completionTime
						? moment(childActivityOther?.completionTime).format(
								'YYYY-MM-DD',
						  )
						: null,
				})
			}
			if (childMaterialObject?.current) {
				let rewardDetailsList: any
				if (materialObjectBise.releaseTime !== 3) {
					rewardDetailsList = [
						{
							leaseTerm: null,
							examinationInterval:
								materialObjectBise?.examinationInterval,
							entityType: materialObjectBise.entityType,
							issueKind: materialObjectBise.issueKind,
							extendedRentalDays: null,
							amount: materialObjectBise?.amount,
						},
					]
				} else {
					rewardDetailsList = childMaterialObject?.current
						?.getList()
						?.map((item: any) => {
							const newItem = item
							if (newItem?.id?.toString().includes('ID')) {
								delete newItem.id
							}
							newItem.examinationInterval =
								materialObjectBise?.examinationInterval
							return newItem
						})
				}
				result.push({
					activitiesType: 2,
					...materialObjectBise,
					rewardDetailsList,
					...materialObjectOther,
					completionTime: materialObjectOther?.completionTime
						? moment(materialObjectOther?.completionTime).format(
								'YYYY-MM-DD',
						  )
						: null,
				})
			}
			if (childRentFree?.current) {
				let rewardDetailsList: any
				if (rentFreeBise.releaseTime !== 3) {
					rewardDetailsList = [
						{
							leaseTerm: null,
							examinationInterval:
								rentFreeBise?.examinationInterval,
							entityType: null,
							issueKind: null,
							extendedRentalDays: null,
							amount: rentFreeBise?.amount,
						},
					]
				} else {
					rewardDetailsList = childRentFree?.current
						?.getList()
						?.map((item: any) => {
							const newItem = item
							if (newItem?.id?.toString().includes('ID')) {
								delete newItem.id
							}
							newItem.examinationInterval =
								rentFreeBise?.examinationInterval
							return newItem
						})
				}

				result.push({
					activitiesType: 3,
					...rentFreeBise,
					rewardDetailsList,
				})
			}
			if (childDeferredRent?.current) {
				const rewardDetailsList: any = [
					{
						leaseTerm: null,
						examinationInterval:
							deferredRentBise?.examinationInterval,
						entityType: null,
						issueKind: null,
						extendedRentalDays:
							deferredRentBise?.extendedRentalDays,
						amount: deferredRentBise?.amount,
					},
				]
				result.push({
					activitiesType: 4,
					...deferredRentBise,
					rewardDetailsList,
				})
			}
			callBack(result)
		},
	}))

	const removePanel = (value: number) => {
		const n = noActiveList?.filter(
			(item: any) => Number(value) !== Number(item),
		)
		const l = activeTypeList?.filter(
			(item: any) => !n?.includes(item.value),
		)
		setActiveList(l)
		setNoActiveList(n)
	}

	return (
		<div className={styles.rewardInfo}>
			<div className={styles.titleBox}>
				奖励信息
				{routerQuery.pageType === 'add' && noActiveList.length !== 4 ? (
					<Button
						type="primary"
						size="small"
						onClick={() => setVisible(true)}>
						新增
					</Button>
				) : null}
			</div>
			<div className={styles.admittanceAdd}>
				<div className={`${styles.content} ${styles.formDetils}`}>
					{activeList?.length !== 4 ? (
						<Row gutter={16}>
							<Col span={24}>
								<Collapse
									defaultActiveKey={['1', '2', '3', '4']}
									ghost
									expandIconPosition="end">
									{noActiveList.includes(1) ? (
										<Panel
											header={customizeHeader(
												'活动类型: 返现',
											)}
											key="1"
											extra={
												<Popconfirm
													placement="topLeft"
													title="你确定要删除这条数据吗？"
													onConfirm={() => {
														removePanel(1)
													}}
													okText="确定"
													cancelText="取消">
													{routerQuery.pageType !==
														'detail' &&
													routerQuery.pageType !==
														'process' &&
													routerQuery.pageType !==
														'edit' ? (
														<Button
															type="link"
															size="small"
															onClick={(
																e: any,
															) => {
																e.stopPropagation()
															}}>
															删除
														</Button>
													) : null}
												</Popconfirm>
											}>
											<div className="formItem">
												<ActivityCashback
													key={1}
													routerQuery={routerQuery}
													detail={detailRecord}
													cRef={childActivityCashback}
												/>
											</div>
										</Panel>
									) : null}
									{noActiveList.includes(2) ? (
										<Panel
											header={customizeHeader(
												'活动类型：实物',
											)}
											key="2"
											extra={
												<Popconfirm
													placement="topLeft"
													title="你确定要删除这条数据吗？"
													onConfirm={() => {
														removePanel(2)
													}}
													okText="确定"
													cancelText="取消">
													{routerQuery.pageType !==
														'detail' &&
													routerQuery.pageType !==
														'process' &&
													routerQuery.pageType !==
														'edit' ? (
														<Button
															type="link"
															size="small"
															onClick={(
																e: any,
															) => {
																e.stopPropagation()
															}}>
															删除
														</Button>
													) : null}
												</Popconfirm>
											}>
											<div className="formItem">
												<MaterialObject
													key={2}
													routerQuery={routerQuery}
													detail={detailRecord}
													cRef={childMaterialObject}
												/>
											</div>
										</Panel>
									) : null}
									{noActiveList.includes(3) ? (
										<Panel
											header={customizeHeader(
												'活动类型：免租',
											)}
											key="3"
											extra={
												<Popconfirm
													placement="topLeft"
													title="你确定要删除这条数据吗？"
													onConfirm={() => {
														removePanel(3)
													}}
													okText="确定"
													cancelText="取消">
													{routerQuery.pageType !==
														'detail' &&
													routerQuery.pageType !==
														'process' &&
													routerQuery.pageType !==
														'edit' ? (
														<Button
															type="link"
															size="small"
															onClick={(
																e: any,
															) => {
																e.stopPropagation()
															}}>
															删除
														</Button>
													) : null}
												</Popconfirm>
											}>
											<div className="formItem">
												<RentFree
													key={3}
													routerQuery={routerQuery}
													detail={detailRecord}
													cRef={childRentFree}
												/>
											</div>
										</Panel>
									) : null}
									{noActiveList.includes(4) ? (
										<Panel
											header={customizeHeader(
												'活动类型：延租',
											)}
											key="4"
											extra={
												<Popconfirm
													placement="topLeft"
													title="你确定要删除这条数据吗？"
													onConfirm={() => {
														removePanel(4)
													}}
													okText="确定"
													cancelText="取消">
													{routerQuery.pageType !==
														'detail' &&
													routerQuery.pageType !==
														'process' &&
													routerQuery.pageType !==
														'edit' ? (
														<Button
															type="link"
															size="small"
															onClick={(
																e: any,
															) => {
																e.stopPropagation()
															}}>
															删除
														</Button>
													) : null}
												</Popconfirm>
											}>
											<div className="formItem">
												<DeferredRent
													key={4}
													routerQuery={routerQuery}
													detail={detailRecord}
													cRef={childDeferredRent}
												/>
											</div>
										</Panel>
									) : null}
								</Collapse>
							</Col>
						</Row>
					) : null}
				</div>
			</div>

			<Modal
				title="司机奖励活动类型"
				open={visible}
				onCancel={() => {
					rewardInfoFrom.resetFields()
					setVisible(false)
				}}
				width={500}
				onOk={() => {
					onActiveTypeChange()
				}}>
				<Form
					layout="horizontal"
					labelCol={{flex: '100px'}}
					labelAlign="right"
					autoComplete="off"
					name="PersonalInformationFom"
					form={rewardInfoFrom}>
					<Form.Item
						label="活动类型"
						name="activeType"
						rules={[{required: true}]}>
						<Select
							allowClear
							placeholder="请选择活动类型"
							options={[...activeList]}
						/>
					</Form.Item>
				</Form>
			</Modal>
		</div>
	)
}
export default rewardInfo
